<template>
  <el-card class="box-card">
    <!-- 添加按钮 -->
    <el-button :icon="Plus" type="primary" @click="dialogVisible = true"
      >添加品牌</el-button
    >
    <!-- 展示表格 -->
    <el-table
      :data="trademarkList"
      :border="true"
      class="table-form"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="70" :align="'center'">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
      <el-table-column prop="name" label="品牌LOGO" align="center">
        <template #default="{ row }">
          <div class="demo-image__error">
            <el-image class="logo-img" :src="row.logoUrl" fit="contain" lazy>
              <template #error>
                <div class="image-slot">
                  <el-icon><icon-picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" align="center">
        <template #default="{ row }">
          <el-tooltip content="编辑品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="warning"
              :icon="Edit"
              @click="editTrandemark(row)"
            />
          </el-tooltip>
          <el-tooltip content="删除品牌" placement="top" effect="light">
            <div class="del-trandmark">
              <el-popconfirm
                title="确定要删除吗?"
                @confirm="delTrandmark(row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger" :icon="Delete" />
                </template>
              </el-popconfirm>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      class="pagination"
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      :small="true"
      layout="  prev, pager, next, jumper,sizes,total,"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.id ? '编辑品牌' : '添加品牌'"
      width="40%"
      @closed="dialogClose"
    >
      <!-- 表单结构 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        ref="trandeMarkForm"
      >
        <!-- 品牌名称 -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="ruleForm.tmName" class="tradeName-input" />
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.logoUrl"
              :src="ruleForm.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTrandemark">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'TrandeMarkList',
}
</script>

<script lang="ts" setup>
import {
  Plus,
  Edit,
  Delete,
  Picture as IconPicture,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormRules, UploadProps, FormInstance } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'

import {
  getTrademarkList,
  addTrademarkApi,
  delTrademarkApi,
  editTrademarkApi,
} from '@/api/product/trademark'
import type {
  TrademarkList,
  TrademarkItem,
} from '@/api/product/model/TrademarkType'

// 修改品牌信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓开始
const editTrandemark = async (trademark: TrademarkItem) => {
  dialogVisible.value = true
  ruleForm.logoUrl = trademark.logoUrl
  ruleForm.tmName = trademark.tmName
  ruleForm.id = trademark.id
}
// 发送请求的逻辑和增加的逻辑在一起
// 修改品牌信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑结束
// 删除品牌信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓开始
const delTrandmark = async (id: number) => {
  await delTrademarkApi(id) // 删除数据的请求
  ElMessage({
    message: '删除成功',
    grouping: true,
    type: 'success',
    center: true,
  })
  // 重新请求数据
  getTrademarkListData()
}
// 删除品牌信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑结束

// 表单数据 --------------------------------------开始
const ruleForm = reactive({
  tmName: '',
  logoUrl: '',
  id: 0,
})
// 弹出框-状态
const dialogVisible = ref(false)
// 弹出框关闭时的回调，清除表单中的数据
const dialogClose = () => {
  console.log('表单中的数据', trandeMarkForm.value)
  trandeMarkForm.value?.resetFields()
  ruleForm.tmName = ''
  ruleForm.logoUrl = ''
  ruleForm.id = 0
}
// 表单组件实例
const trandeMarkForm = ref<FormInstance>()
// 表单验证规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 10, message: '你看看你的字数对吗？', trigger: 'blur' },
  ],
  logoUrl: [{ required: true, message: '图片必须上传', trigger: 'change' }],
})
// 表单数据-----------------------------------------结束

// 上传图片相关---------------------------------------开始
// 上传图片地址：从.env.development中加载的
const BASE_URL = import.meta.env.VITE_API_URL
// 图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.logoUrl = response.data
}
// 图片上传之前的准备
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片格式只能是 JPG 或 PNG!')
    return false
  } else if (rawFile.size / 1024 > 500) {
    ElMessage.error('不能超过500kb！！')
    return false
  }
  return true
}
// 上传图片相关-------------------------------------------结束

// 添加品牌信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓开始
const addTrandemark = () => {
  // 先触发 一波表单校验
  trandeMarkForm.value?.validate(async (valid) => {
    if (valid) {
      //表单校验成功
      if (ruleForm.id) {
        await editTrademarkApi(ruleForm)
        ElMessage.success('修改成功')
      } else {
        await addTrademarkApi(ruleForm) // 添加品牌数据
      }
      ElMessage({
        message: '品牌数据' + (ruleForm.id ? '修改' : '添加') + '成功',
        grouping: true,
        type: 'success',
        center: true,
      })

      // 关闭弹出框
      dialogVisible.value = false
      // 清空表单数据
      // trandeMarkForm.value?.resetFields()
      // 重新发送请求获取最新数据
      getTrademarkListData()
    }
  })
}
// 添加品牌信息--------↑↑↑↑↑↑↑↑↑----------↑↑↑结束

// 加载中
const loading = ref(false)
// 当前页
const currentPage = ref(1)
// pageSize
const pageSize = ref(3)
// 数据总数
const total = ref(0)
// 平牌数据
const trademarkList = ref<TrademarkList>([])

// 请求数据的方法
const getTrademarkListData = async () => {
  loading.value = true
  const res = await getTrademarkList(currentPage.value, pageSize.value)
  trademarkList.value = res.records
  total.value = res.total
  ElMessage({
    message: '品牌数据请求成功',
    grouping: true,
    type: 'success',
    center: true,
  })
  loading.value = false
}

// 组件挂载请求数据
onMounted(async () => {
  getTrademarkListData()
})

// 页面内容数量
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getTrademarkListData()
}
// 页码改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getTrademarkListData()
}

/* // 图片加载失败
const errorHandler = () => {
  console.log(123213)
} */
</script>

<style scoped lang="scss">
.del-trandmark {
  display: inline-block;
  margin-left: 10px;
}
.table-form {
  margin: 20px 0;
}
.logo-img {
  height: 54px;
}
.tradeName-input {
  width: 300px;
}

// 品牌图片/加载失败的样式
.demo-image__error .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 49%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image__error .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.demo-image__error .el-image {
  padding: 0 5px;
  max-width: 150px;
  max-height: 100px;
  width: 100%;
  height: 200px;
}
.demo-image__error .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

// 上传图片的样式----全局还有
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
